<?php

namespace App\Http\Controllers;
use App\Models\AddressBook;
use App\Models\AdminUser;
use App\Models\AutoFollowPlan;
use App\Models\CaseDescribe;
use App\Models\Course;
use App\Models\Doctor;
use App\Models\DoctorWorks;
use App\Models\Evaluate;
use App\Models\FinancialStatementsLog;
use App\Models\GroupAssistantLog;
use App\Models\HealthReminder;
use App\Models\MidPhoneLog;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\PlanMessage;
use App\Models\ProductGoods;
use App\Models\Store;
use App\Models\StoreOrder;
use App\Service\Push;
use App\User;
use App\Util\Tool;
use Carbon\Carbon;
use Illuminate\Config;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Mrgoon\AliSms\AliSms;

/***
 * Class WxPayController
 * @package App\Http\Controllers
 *
 * 脚本处理
 */
class RunController extends BaseController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * @return array
     * 收货后7天自动评价
     */
    private  static function setEvaluateToArrivedTime()
    {
        $order = new Order();
        $order_goods = new OrderGoods();
        $evaluate =  new Evaluate();
        $orderinfo = $order->whereIn("order_type",[1,2])->where([['order_status','=',1],['evaluate_status','=',0]])->orderBy("id","desc")->get();
        if(empty($orderinfo)){
            return [];
        }
        $log = [];
        foreach($orderinfo as $k=>$v) {
            if ($v->pay_status == 1 && $v->delivery_status == 1 && $v->receive_status == 1 && $v->evaluate_status == 0) {
                //确认收货后多长时间,自动评价
                $days = self::handelTime($v->receive_time);
                if ($days['day'] >= 7) {
                    $dt['evaluate_status'] = 1;
                    $dt['evaluate_time'] = date("Y-m-d H:i:s", time());
                    $o_goods = $order_goods->where([['order_id', '=', $v->id]])->first();
                    $eval["order_id"] = $v->id;
                    $eval["user_id"] = $v->user_id;
                    $eval["work_id"] = $v->work_id;
                    $eval["goods_id"] = $o_goods->goods_id;
                    $eval["service_score"] = 5;
                    if($v->order_type ==2){
                        $eval["logis_score"] = 5;
                        $eval["delivery_score"] = 5;
                    }
                    $eval["content"] = "此用户未添加文本!";
                    $eval["types"] = $v->order_type;
                    $info = $evaluate->where([['order_id','=',$v->id]])->first();
                    if(empty($info)){
                        $evaluate->addEvaluateContent($eval);
                    }
                    $order->where([['id', '=', $v->id]])->update($dt);
                    $log[] = $v->id;
                }
            }
        }
        return $log;
    }

    /***
     * 普通订单(商品订单,课程订单)
     *订单生成1小时未付款自动取消
     * 7天未发货自动退回,取消订单
     * 发货后15天不确认收货,自动收货
     */
    private static function handelGeneralOrder()
    {
        $order = new Order();
        $order_goods = new OrderGoods();
        $goods = new ProductGoods();
        $payment =  new PaymentController();
        $wxPay =   new WxPayController();
        $orderinfo = $order->whereIn("order_type",[1,2])->where([['order_status','=',0]])->orderBy("id","desc")->get();
        if(empty($orderinfo)){
            return [];
        }
        $log = [];
        foreach($orderinfo as $k=>$v){
            if($v->pay_status == 0){
                //判断订单下单时间
                $days = self::handelTime($v->created_at);
                if($days['hour'] >=1){
                    //取消订单
                    $order->where([['id','=',$v->id]])->update(['order_status'=>4]);
                    $log[] = $v->id;
                }
            }elseif ($v->pay_status == 1 && $v->delivery_status == 0 && $v->order_status == 0){
                if($v->order_type == 1){  //课程类型跳过
                    continue;
                }
                //判断付款后7天时间没有发货,自动取消订单
                $days = self::handelTime($v->pay_time);


                if($days['day'] >=7){
                    //需要退款
                    if($v->pay_type ==1){   //微信退款
                        $lit['sn'] = $v->sn;
                        $lit['price'] = $v->order_price;
                        $lit['return_sn'] = $order->orderNumber();
                        $stu = $wxPay->returnBack($lit);
                        if($stu == "refund" && ($v->order_status == 1 || $v->order_status == 0) ){
                            //如果钱已退,修改订单状态
                            (new Order())->where([['id', '=', $v->id]])->update(['order_status' => 4]);
                        }
                        $log[] = $v->id;
                        continue;
                    }elseif ($v->pay_type ==2){  //支付宝退款
                        $lit['sn'] = $v->sn;
                        $lit['money'] = $v->order_price;
                        $lit['back_sn'] = $order->orderNumber();
                        $back = $payment->doReturn($lit);
                    }
                    if ($back == true) {
                        //退回账单
                        (new FinancialStatementsLog())->setGoodsOrderBack($v->id);
                        //取消订单
                        $order->where([['id', '=', $v->id]])->update(['order_status' => 4]);
                        //增加库存
                        $o_goods = $order_goods->where([['order_id', '=', $v->id]])->first();
                        $goods->where([['id', '=', $o_goods->goods_id]])->decrement("product_stock", $o_goods->goods_num);
                        $log[] = $v->id;
                    }
                }
            }elseif ($v->pay_status == 1 && $v->delivery_status==1  && $v->receive_status == 0 && $v->order_status == 0){
                //发货后超过时间不确认收货,自动收货
                $days = self::handelTime($v->delivery_time);
                if ($days['day'] >= 15) {
                    //如果过已确认收货,跳过
                    if ($v->receive_status == 1) {
                        continue;
                    }
                    $dt['receive_status'] = 1;
                    $dt['receive_time'] = date("Y-m-d H:i:s", time());
                    $dt["order_status"] = 1;
                    (new FinancialStatementsLog())->goodsOrderconfirmReceipt($v->id); //商品自动确认收货
                    $order->where([['id', '=', $v->id]])->update($dt);
                    $log[] = $v->id;
                }
            }
        }
        return $log;
    }

    /***
     * 咨询订单
     * 预约咨询时间到,未接单的自动取消订单,金额退回
     * 接单了,到时间,未开始咨询的,自动退单
     * 咨询时长已到,未结束咨询的自动结束订单
     */
    private function handelConsultOrder()
    {
        $order = new Order();
        $order_goods = new OrderGoods();
        $payment =  new PaymentController();
        $wxPay = new WxPayController();
        $financialStatementsLog =  new FinancialStatementsLog();
        $orderinfo = $order->whereIn("order_type",[3,4])->where([['order_status','=',0],['pay_status','=',1]])->orderBy("id","desc")->get();
        if(empty($orderinfo)){
            return [];
        }
        $log = [];
        foreach($orderinfo as $k=>$v){
            //判断开始咨询时间
            if($v->delivery_status == 0){   //预约咨询时间到,未接单的自动取消订单,金额退回
                $o_goods = $order_goods->where([['order_id','=',$v->id]])->first();
                if ($v->consult_type == 2) {   //预约咨询
                    $days = self::handelTime($o_goods->rever_date . " " . $o_goods->rever_time);
                    if ($days['diff'] == 1) {
                        $this->sendMessageToUser($v,$o_goods); //发送短信
                        //退款
                        if ($v->pay_type == 1) {   //微信退款
                            $lit['sn'] = $v->sn;
                            $lit['price'] = $v->order_price;
                            $lit['return_sn'] = $order->orderNumber();
                            $wxPay->returnBack($lit);
                            $log[] = $v->id;
                            continue;
//                        if($bac == "退款成功"){
//                            $back = true;
//                        }
                        } elseif ($v->pay_type == 2) {  //支付宝退款
                            $lit['sn'] = $v->sn;
                            $lit['money'] = $v->order_price;
                            $lit['back_sn'] = $order->orderNumber();
                            $back = $payment->doReturn($lit);
                        }
                        if ($back) {
                            //添加账单记录
                            $financialStatementsLog::setBackConsultOrder($v, $o_goods);
                            $order->where([['id', '=', $v->id]])->update(['order_status' => 4]);
                            $log[] = $v->id;
                        }
                    }
                }else if($v->consult_type == 1){ //问诊病例
                //付款一个小时后未接单自动取消订单
                    if(time() - strtotime($v->pay_time) > 1800){ // 一小时后还没有接单自动取消订单
                        $this->sendMessageToUser($v,$o_goods); //发送短信
                        //退款
                        if ($v->pay_type == 1) {   //微信退款
                            $lit['sn'] = $v->sn;
                            $lit['price'] = $v->order_price;
                            $lit['return_sn'] = $order->orderNumber();
                            $wxPay->returnBack($lit);
                            $log[] = $v->id;
                            continue;
//                        if($bac == "退款成功"){
//                            $back = true;
//                        }
                        } elseif ($v->pay_type == 2) {  //支付宝退款
                            $lit['sn'] = $v->sn;
                            $lit['money'] = $v->order_price;
                            $lit['back_sn'] = $order->orderNumber();
                            $back = $payment->doReturn($lit);
                        }
                        if ($back) {
                            //添加账单记录
                            $financialStatementsLog::setBackConsultOrder($v, $o_goods);
                            $order->where([['id', '=', $v->id]])->update(['order_status' => 4]);
                            $log[] = $v->id;
                        }
                    }
                }
            }elseif ($v->delivery_status == 1 && $v->receive_status == 0){
                $o_goods = $order_goods->where([['order_id', '=', $v->id]])->first();
                if ($v->consult_type == 2) {   //预约咨询
                    $start = $o_goods->rever_date . " " . $o_goods->rever_time;
                    if (strtotime($start) > 0 && time() > strtotime($start) && $v->consult_status == 0) {   //接单了,到时间,未开始咨询的,自动退单
                        $this->sendMessageToUser($v,$o_goods); //发送短信
                        //退款
                        if ($v->pay_type == 1) {   //微信退款
                            $lit['sn'] = $v->sn;
                            $lit['price'] = $v->order_price;
                            $lit['return_sn'] = $order->orderNumber();
                            $wxPay->returnBack($lit);
                            continue;
//                        if($bac == "退款成功"){
//                            $back = true;
//                        }
                        } elseif ($v->pay_type == 2) {  //支付宝退款
                            $lit['sn'] = $v->sn;
                            $lit['money'] = $v->order_price;
                            $lit['back_sn'] = $order->orderNumber();
                            $back = $payment->doReturn($lit);
                        }
                        if ($back) {
                            //添加账单记录
                            $financialStatementsLog::setBackConsultOrder($v, $o_goods);
                            $order->where([['id', '=', $v->id]])->update(['order_status' => 4]);
                            $log[] = $v->id;
                        }
                        continue;
                    }
                }
                //咨询开始时间
                if (empty($v->consult_time)) {  //还没有开始咨询跳过
                    continue;
                }
                $time = floor((time() - strtotime($v->consult_time)) / 60);
                if ($v->order_type == 3) {
                    //剩余5分钟时候提醒消息
                    if (($o_goods->duration - $time == 5 || $o_goods->duration - $time == 2 || $o_goods->duration - $time == 1) && $v->consult_status == 1) {
                        (new Easemob())->sendGroupText("admin", $v->chatgroup_id, "本次咨询即将结束,如需要加时,请医师加时,时间到达后,本聊天室将自动解散,订单将自动完成!");
                    }
                }
                if (($time > $o_goods->duration) && $v->consult_status == 1) {   //咨询时长已到,未结束咨询的自动结束订单
                    if($v->order_type== 3){ //图文
                        (new Easemob())->sendGroupText("admin", $v->chatgroup_id, "本次咨询已结束,祝您生活愉快!");
                        $dl["receive_status"] = 1;
                        $dl["receive_time"] = date("Y-m-d H:i:s", time());
                        $dl["consult_status"] = 2;
                        $dl["order_status"] = 1;
                        $dl['consult_end'] = 2; //到时结束
                        $diff_time = time() - strtotime($v->consult_time);
                        $du_time = $o_goods->duration * 60;
                        if($diff_time >= $du_time){
                            $second = $o_goods->duration;
                            if($second <10){
                                $minute = "00";
                                $second = '0'.$second;
                            }else{
                                $minute = $o_goods->duration;
                                $second = '00';
                            }
                        }else{
                            $minute = floor($diff_time % 86400 / 60);
                            $second = floor($diff_time % 86400 % 60);
                            if($second <10){
                                $second = '0'.$second;
                            }
                        }
                        $dl['use_time'] = $minute . ":" . $second;
                        (new FinancialStatementsLog())::setCompleteConsultOrder($v, $dl);
                        $order->where([['id', '=', $v->id]])->update($dl);
                        //解散群组
                        $filter['order_id'] = $v->id;
                        (new Easemob())->dissolveChatRoom($filter);
                    }elseif ($v->order_type== 4){ //电话咨询
                        $dl["receive_status"] = 1;
                        $dl["receive_time"] = date("Y-m-d H:i:s", time());
                        $dl["consult_status"] = 2;
                        $dl["order_status"] = 1;
                        $dl['consult_end'] = 2; //到时结束
                        $diff_time = time() - strtotime($v->consult_time);
                        $minute = floor($diff_time % 86400 / 60);
                        $second = floor($diff_time % 86400 % 60);
                        $dl['use_time'] = $minute . ":" . $second;
                        (new FinancialStatementsLog())::setCompleteConsultOrder($v, $dl);
                        $order->where([['id', '=', $v->id]])->update($dl);
                        //解绑小号
                        $user = (new User())->where([['id', '=', $v->user_id]])->first();
                        $dt['mid_phone'] = config("omnipay.Numbers");
                        $doc = (new Doctor())->where([['id', '=', $o_goods->goods_id]])->first();//$o_goods->phone;
                        $dt['a_phone'] = $doc->account;
                        $dt['b_phone'] = $user->phone;
                        (new AxCallController())->doAxUnbind($dt); //解绑小号
                        (new MidPhoneLog())->where([['order_id','=',$v->id]])->update(['state'=>0]);
                    }
                    $log[] = $v->id;
                }
            }
        }
        return $log;
    }

    /**
     * @param $order
     * @param $o_goods
     * @throws \Exception
     * 发送用户短信
     */
    public function sendMessageToUser($order, $o_goods)
    {
        //给用户发送短信医生已决绝
        $ali_sms = new AliSms();
        $phone = (new User())->where([['id', '=', $order->user_id]])->value("phone");
        $paras['name'] = $o_goods->goods_name;
        //给用户发送短信
        $ali_sms::sendMessage($phone, $paras, 2);
        return true;
    }
    /**
     * @param $time
     * @return float
     * 计算天数
     */
    public static function handelTime($time)
    {
        $start = strtotime($time);
        $end = time();
        $day = number_format(($end - $start) / 86400,1);
        $hour = number_format(($end - $start)%86400/3600,1);
        $diff = $end - $start;
        $data['diff']  = 0;
        if($diff>=0){
            $data['diff']  = 1;
        }
        $data['day']  = $day;
        $data['hour']  = $hour;
        return $data;
    }

    /***
     *
     *定时发送自动随访计划
     *
     */
    public function doSendAutoFollowUp()
    {
        $follow = new AutoFollowPlan();
        $plan_message = new PlanMessage();
        $plan = $follow->where([['type', '!=', 2]])->get();
        if (empty($plan)) {
            return [];
        }
        $logs = [];
        foreach ($plan as $k => $v) {
            $mess = $plan_message->where([["auto_follow_plan_id", '=', $v->id], ['is_send', '=', 0]])->get();
            foreach ($mess as $kk => $vv) {
                $s_time = strtotime($vv->date);
                //到时间,发送消息
                if (date("Y-m-d H:i", $s_time) == date("Y-m-d H:i", time())) {
                    $send_user = $this->sendMessage($vv);
                    if ($send_user == true) {
                        $logs[] = $vv->id;
                        $plan_message->where([["id", '=', $vv->id], ['is_send', '=', 0]])->update(['is_send' => 1]);
                    }
                }
//                如果时间已过,设为已发送
                if ($s_time < time()) {
                    $logs[] = $vv->id;
                    $plan_message->where([["id", '=', $vv->id], ['is_send', '=', 0]])->update(['is_send' => 1]);
                }
            }
//            判断消息是否全部发送完
            $num = $plan_message->where([["auto_follow_plan_id", '=', $v->id], ['is_send', '=', 0]])->count();
            if ($num == 0) {
                $follow->where([['id', '=', $v->id]])->update(['type' => 2]);
            }else{
                $follow->where([['id', '=', $v->id]])->update(['type' => 1]);
            }
        }
        return $logs;
    }

    /***
     * @param $plan_mess
     * 发送消息
     */
    public function sendMessage($plan_mess)
    {
        $users = (new GroupAssistantLog())->where([['group_assistant_id', '=', $plan_mess->auto_follow_plan_id], ['type', '=', 3]])->get();
        $easemob = new Easemob();
        $user_ids = [];
        $push = new Push();
        foreach ($users as $k => $v) {
            //发送消息
            $user_ids[] = 'user_' . config("omnipay.Im.salt") . $v->user_id;
            //推送消息
            $lt['type'] = 1;
            $lt['user_id'] = $v->user_id;
            $lt['title'] = "自动随访提醒";
            $lt['content'] = "您收到自动随访消息提醒,请及时查看消息内容!";
            $push->pushToUser($lt);
        }
        //发送消息
        $lst['username'] = $user_ids;
        $lst['text'] = $plan_mess->message;
        $easemob->sendTextBySdk($lst);
        //推送消息
        $lit['user'] = $user_ids;
        $lit['title'] = "自动随访提醒";
        $lit['sub_title'] = "自动随访提醒";
        $lit['content'] = "您收到自动随访消息提醒,请及时查看消息内容!";
        $easemob->sendSinglePush($lit);
        return true;
    }

    /**
     * @return array
     * 商圈到时间取消置顶状态
     */
    public static function setStoreStatus()
    {
        $store = new Store();
        $store_order = new StoreOrder();
        $result = $store->where([['is_online','=',1]])->get();
        $logs = [];
        if (!empty($result)) {
            $push = new Push();
            foreach ($result as $k => $v) {
                $data = $store_order->where([['store_id','=',$v->id]])->first();
                if(empty($data)){
                    continue;
                }
                $day = self::getDiffTime(strtotime($data->pay_time));
                if($day > $data->days){
                    //推送消息
                    $lt['type'] = 1;
                    $lt['user_id'] = $v->user_id;
                    $lt['title'] = "商圈提醒";
                    $lt['content'] = "您购买的商圈服务已到期,请及时续费!";
                    $push->pushToUser($lt);
                    $store->where([['id','=',$v->id]])->update(['topping'=>0,'is_online'=>0]);
                    $logs[] = $v->id;
                }
            }
        }
        return $logs;
    }

    public static function getDiffTime($time)
    {
        return floor((time() - $time)/ 86400);
        
    }

    /**
     * 推送用药提醒
     */
    private static function setPushMessage()
    {
        $health = new HealthReminder();
        $date = Carbon::today();
        $result = $health->where([['status', '=', 1], ['end_time', '>=', $date],['start_time', '<=', $date]])->get();
        $logs = [];
        if (!empty($result)) {
            $time = date("H:i", time());
            $easemob = new Easemob();
            $user_ids = [];
            $push =new Push();
            foreach ($result as $k => $v) {
                if (empty($v->take_time)) {
                    continue;
                }
                if (in_array($time, $v->take_time)) {
                    $user_ids[] = 'user_' . config("omnipay.Im.salt") . $v->user_id;
                    $logs[] = $v->id;
                    //推送消息
                    $lt['type'] = 1;
                    $lt['user_id'] =$v->user_id;
                    $lt['title'] = "用药提醒";
                    $lt['content'] = "温馨提示！用药提醒，您设置的用药时间：".$time.",药品为".$v->name."，请记得按时用药！";
                    $res = $push->pushToUser($lt);
                }
            }
            if (count($user_ids) > 0) {
                $lit['user'] = $user_ids;
                $lit['title'] = "用药提醒";
                $lit['sub_title'] = "用药提醒";
                $lit['content'] = "您设置的用药时间已到,请及时用药";
                $nill = $easemob->sendSinglePush($lit);
                (new PaymentController())->writeLog($nill);
            }
        }
        return $logs;
    }

    /**
     * @return string
     * @throws \Exception
     * 批量设置医护是否在线
     */
    private function setisDoctorOnline()
    {
        return (new Easemob())->isUsersOnline();
    }

    /**
     *
     * 脚本自动处理入口
     */
    public function run()
    {
        $general = self::handelGeneralOrder();//普通订单(商品订单,课程订单)
        $evaluate = self::setEvaluateToArrivedTime(); //自动评价
        $consult = self::handelConsultOrder();//咨询订单
        echo "本次处理订单ID:" . json_encode(array_merge($general, $consult, $evaluate)) . "<br/>";
        $logs = self::doSendAutoFollowUp();//自动随访发送消息
        echo "本次发送随访消息c_plan_messages_ID:" . json_encode($logs);
        $ids = self::setStoreStatus();  //设置商圈是否过时
        echo "本次处理商圈ID:" . json_encode($ids);
        $push_log = self::setPushMessage(); //定时推送消息
        echo "本次推送健康提醒ID:" . json_encode($push_log);
        $isline_log = self::setisDoctorOnline(); //定时推送消息
        echo "本次设置医护环信在线记录:" . json_encode($isline_log);
    }
    
    


    
}
